//
//  SystemSetViewController.m
//  安好
//
//  Created by 冯凯 on 14-11-21.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "SystemSetViewController.h"
#import "SystemSettingTableViewCell.h"
#import "MessageSetViewController.h"
#import "SoundViewController.h"
#import "OpinionViewController.h"
#import "PrivacyViewController.h"
#import "DisclaimerViewController.h"
#import "LaunchView.h"
#import "XGPush.h"
#import "ConsultViewController.h"
#import "LCStatusBarOverlay.h"
#import "AppDelegate.h"
@interface SystemSetViewController ()

@end

@implementation SystemSetViewController

/**
 *  进入页面的是否  判断是否存在需要上传到消息通知或者是隐私设置
 *
 *  @param animated 无
 */
- (void)viewWillAppear:(BOOL)animated
{
    [self.systemTableView reloadData];
}
- (void)viewDidAppear:(BOOL)animated
{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
    NSString *pushmess= [NSString stringWithFormat:@"Pushmess%@",uid];
    BOOL pussMess = [user boolForKey:pushmess];
    if (pussMess == YES){
        [self loadWithData];
    }
    NSString * privacy = [NSString stringWithFormat:@"Privaty%@",uid];
    
    if ([[user objectForKey:privacy] length] != 0){
        [self loadWithPriData];
    }
    
}
#pragma - mark 上传隐私设置
/**
 *  上传隐私设置
 */
- (void)loadWithPriData
{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString * postURL = [NSString stringWithFormat:@"%@user/lnglatsystem/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
    NSString * pushNewKey = [NSString stringWithFormat:@"AllNear%@",uid];
    NSString * pushAnKey = [NSString stringWithFormat:@"AnNear%@",uid];
    NSString * pushDicKey = [NSString stringWithFormat:@"DoctionNear%@",uid];
    NSString * pushNew =[user objectForKey:pushNewKey];
    if ([[user objectForKey:pushNewKey] isEqualToString:@"3"] || [[user objectForKey:pushNewKey] length] == 0){
        if ([[user objectForKey:pushAnKey] isEqualToString:@"1"]&& [[user objectForKey:pushDicKey] isEqualToString:@"2"])
        {
            pushNew = @"3";
        }else if ([[user objectForKey:pushAnKey] isEqualToString:@"0"]&& [[user objectForKey:pushDicKey] isEqualToString:@"0"]){
            pushNew = @"4";
        }else if ([[user objectForKey:pushAnKey] length] == 0 && [[user objectForKey:pushDicKey] length]== 0){
            pushNew = @"2";
        }else if ([[user objectForKey:pushAnKey] length] == 0 && [[user objectForKey:pushDicKey] isEqualToString:@"2"]){
            pushNew = @"2";
        }else if ([[user objectForKey:pushAnKey] isEqualToString:@"0"] && [[user objectForKey:pushDicKey] isEqualToString:@"2"]){
            pushNew = @"2";
        }else if ([[user objectForKey:pushAnKey] isEqualToString:@"1"] && [[user objectForKey:pushDicKey] length]== 0){
            pushNew = @"1";
        }else if ([[user objectForKey:pushAnKey] isEqualToString:@"1"] && [[user objectForKey:pushDicKey] isEqualToString:@"0"]){
            pushNew = @"1";
        }else if ([[user objectForKey:pushAnKey] length] == 0 && [[user objectForKey:pushDicKey] isEqualToString:@"0"]){
            pushNew = @"1";
        }
    }else{
        pushNew = @"4";
    }
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"status":pushNew};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"1"]) {
            NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
            NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
            NSString * privacy = [NSString stringWithFormat:@"Privaty%@",uid];
            [user removeObjectForKey:privacy];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];

}
#pragma - mark 消息设置
/**
 *  消息设置
 */
- (void)loadWithData
{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString * postURL = [NSString stringWithFormat:@"%@setting/message/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
    NSString * pushNewKey = [NSString stringWithFormat:@"pushNew%@",uid];
    NSString * pushNew =[user objectForKey:pushNewKey];
    if ([pushNew length] == 0) {
        pushNew = @"1";
    }
    NSString * pushDetailKey = [NSString stringWithFormat:@"pushDetail%@",uid];
    NSString * pushDetail =[user objectForKey:pushDetailKey];
    if ([pushDetail length] == 0) {
        pushDetail = @"1";
    }
    NSString * pushActivityKey = [NSString stringWithFormat:@"pushActivity%@",uid];
    NSString * pushActivity =[user objectForKey:pushActivityKey];
    if ([pushActivity length] == 0) {
        pushActivity = @"0";
    }
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"people":@"1",@"remind":pushNew,@"showdetail":pushDetail,@"avoid":pushActivity};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"1"]) {
            NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
            NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
            NSString *pushmess= [NSString stringWithFormat:@"Pushmess%@",uid];
            [user setBool:NO forKey:pushmess];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //加载导航条
    [self makeNavBar];
    //加载数据
    [self loadData];
    //加载tableView
    [self createTableView];
//    dispatch_queue_t queue = dispatch_get_main_queue();
//    dispatch_async(queue, ^{
//    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
//    NSString *filePath = [cachPath stringByAppendingPathComponent:@"ImageCache"];
//   self.cookieString= [NSString stringWithFormat:@"%.2fM",[self folderSizeAtPath:filePath]];
//    });
    //提示信息用的view
    self.HUDforText = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    self.HUDforText.customView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.navigationController.view.superview addSubview:self.HUDforText];
}
/**
 *  创建数据
 */
-(void)loadData
{
    self.setArray = @[@"铃声设置",@"消息通知",@"隐私设置"];
    self.ideaArray = @[@"意见反馈",@"用户评分",@"检测版本",@"欢迎页面",@"免责声明",@"关于我们"];
    self.logotArray = @[@"退出登录"];
    self.cacheArray = @[@"清除缓存"];
}

#pragma mark - 配置导航条
-(void)makeNavBar
{
    self.navigationItem.title = @"设置";
    // 返回按钮图片
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backMoreVC)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
}
#pragma mark - 创建tableView设置代理
-(void)createTableView
{
    self.systemTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0 , kScreenWidth, kScreenHeight - iOS7TopMargin) style:UITableViewStyleGrouped];
    self.systemTableView.delegate = self;
    self.systemTableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.systemTableView.showsHorizontalScrollIndicator = NO;
    self.systemTableView.showsVerticalScrollIndicator = NO;
    self.systemTableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.view addSubview:self.systemTableView];
}
#pragma - mark 返回
/**
 *  返回
 */
- (void)backMoreVC
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma - mark tableViewDelegate
/**
 *  设置 为 2 段
 */
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return self.setArray.count;
    }else if (section == 1){
        return self.ideaArray.count;
    }else if (section == 3){
        return self.logotArray.count;
    }else{
        return self.cacheArray.count;
    }
}
//设置段头高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (kScreenWidth == 414){
        return 56;
    }else{
        return 44;
    }
}
#pragma mark 2中cell的加载
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SystemSettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SystemSettingTableViewCell"];
    if (cell == nil) {
        if(kScreenWidth == 414){
            cell = [[[NSBundle mainBundle] loadNibNamed:@"SystemSettingTableViewCell" owner:self options:nil] lastObject];

        }else{
        cell = [[[NSBundle mainBundle] loadNibNamed:@"SystemSettingTableViewCell" owner:self options:nil] firstObject];
        }
    }
    if (indexPath.section == 0) {
        if (indexPath.row == 0){
            NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
            NSString * uid = [[UserManager shareInstance]getUserInfo].uid;
            NSString * soundKey = [NSString stringWithFormat:@"Sound%@",uid];
            NSString * sound = [user objectForKey:soundKey];
            if ([sound length] == 0) {
                cell.detailLabel.text = @"默认";
            }else{
                cell.detailLabel.text = sound;

            }
        }
        cell.settingLabel.text = self.setArray[indexPath.row];
    }else if (indexPath.section == 1){
        if (indexPath.row == 2) {
            cell.detailLabel.text = [NSString stringWithFormat:@"当前版本V%@",kVersion];
        }
        cell.settingLabel.text = self.ideaArray[indexPath.row];
    }else if (indexPath.section == 3){
            cell.pushImageView.hidden = YES;
            cell.settingLabel.text = self.logotArray[indexPath.row];
    }else{
//        cell.detailLabel.text = [NSString stringWithFormat:@"%@",self.cookieString];
        cell.settingLabel.text = self.cacheArray[indexPath.row];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 3){
        [self logoutWithData];
    }else if (indexPath.section == 0){
        if (indexPath.row == 0) {
            [self pushSoundView];
        }else if (indexPath.row == 1){
            [self messageSet];
        }else{
            [self PrivacySet];
        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 1){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/hao-kai-qi-jian-kang-xin-sheng/id885697542?l=zh&ls=1&mt=8"]];
        }else if (indexPath.row == 2){
            [self ISChangeVersion];
        }else if (indexPath.row == 3){
            self.navigationController.navigationBar.translucent = YES;
            LaunchView *launchView = [[LaunchView alloc]initWithFrame:self.view.frame];
            launchView.delegate = self;
            self.navigationController.navigationBarHidden = YES;
            [self.view addSubview:launchView];
        }else if (indexPath.row == 0){
            OpinionViewController * opinionViewController = [[OpinionViewController alloc]init];
            [self.navigationController pushViewController:opinionViewController animated:YES];
        }else if (indexPath.row == 4){
            DisclaimerViewController * disclaimerViewController = [[DisclaimerViewController alloc]init];
            [self.navigationController pushViewController:disclaimerViewController animated:YES];
        }else if (indexPath.row == 5){
            DisclaimerViewController * disclaimerViewController = [[DisclaimerViewController alloc]init];
            disclaimerViewController.isFromAboutMe = YES;
            [self.navigationController pushViewController:disclaimerViewController animated:YES];
        }
    }else if (indexPath.section == 2){
        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
        NSString *filePath = [cachPath stringByAppendingPathComponent:@"ImageCache"];

        [self folderSizeAtPath:filePath];

        NSFileManager *defauleManager = [NSFileManager defaultManager];
        [defauleManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        [defauleManager removeItemAtPath:filePath error:nil];
        
        //手动清除家人头像的图片缓存
        [self accordingToInterval:1 withUserDateForKey:@"FamilyHeaderFloderDate" JudgeRemoveFileName:@"FamilyHeaderFloder"];
        //手动清除安好订阅的图片缓存
        [self accordingToInterval:1 withUserDateForKey:@"SubscriptionDate" JudgeRemoveFileName:@"SubscriptionImg"];
        
        
        
        self.cookieString = @"0M";
        [self.systemTableView reloadData];
        [self showLoadingForText:@"清理缓存成功！"];
    }
}
-(void)showLoadingForText:(NSString *)text{
    self.HUDforText.mode = MBProgressHUDModeCustomView;
    self.HUDforText.labelText = text;
    [self.HUDforText show:YES];
    [self.HUDforText hide:YES afterDelay:1];
}

/**
 *  根据保存在NSUserDefaults中的时间和现在的时间的间隔，决定是否删除本地的文件夹
 *
 *  @param interval    规定的时间间隔
 *  @param userDateKey 在NSUserDefault中保存原来日期的key，
 *  @param floderName  在本地沙盒目录下FileManager中的文件夹的名字
 */
-(void)accordingToInterval:(NSTimeInterval)interval withUserDateForKey:(NSString*)userDateKey JudgeRemoveFileName:(NSString*)floderName{
    
    NSUserDefaults * timeUser = [NSUserDefaults standardUserDefaults];
    NSDate * oldTime = [timeUser objectForKey:userDateKey];
    NSDate * nowDate = [NSDate date];
    if (oldTime != nil) {
        NSTimeInterval Timeinterval = [nowDate timeIntervalSinceDate:oldTime];
        if (Timeinterval >= interval) {
            //删除
            //本地沙盒文件路径
            NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
            //保存家人头像的文件夹
            NSString *imagesPath = [documentPath stringByAppendingString:[NSString stringWithFormat:@"/%@/",floderName]];
            if ([[NSFileManager defaultManager] fileExistsAtPath:imagesPath]) {
                [[NSFileManager defaultManager] removeItemAtPath:imagesPath error:nil];
            }
            [timeUser removeObjectForKey:userDateKey];
        }
    }
    
}

#pragma - mark 动画启动页
/**
 *  动画启动页
 *
 *  @param launchView 动画启动页
 */
- (void)launchViewDidFinish:(LaunchView *)launchView
{
    self.navigationController.navigationBarHidden = NO;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.1];
    launchView.alpha = 0;
    [UIView commitAnimations];
    self.navigationController.navigationBar.translucent = NO;
    [launchView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:0.1];
}

#pragma - mark 检测版本
- (void)ISChangeVersion
{
    NSString * postURL = @"https://itunes.apple.com/lookup?id=885697542";
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:postURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString * version = [[[responseObject objectForKey:@"results"] objectAtIndex:0] objectForKey:@"version"];
        if ([kVersion isEqualToString:version]){
            alertContent(@"您的安好是最新的版本");
        }else{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/hao-kai-qi-jian-kang-xin-sheng/id885697542?l=zh&ls=1&mt=8"]];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
#pragma -mark 跳转铃声
- (void)pushSoundView
{
    SoundViewController * soundViewController = [[SoundViewController alloc]init];
    [self.navigationController pushViewController:soundViewController animated:YES];
}
#pragma -mark 消息通知
- (void)messageSet
{
    MessageSetViewController * messageSetViewController = [[MessageSetViewController alloc]init];
    [self.navigationController pushViewController:messageSetViewController animated:YES];
}
#pragma -mark 隐私设置
- (void)PrivacySet
{
    PrivacyViewController * privacyViewController = [[PrivacyViewController alloc]init];
    [self.navigationController pushViewController:privacyViewController animated:YES];
}
#pragma -mark 取消登录
- (void)logoutWithData
{
    NSString * postURL = [NSString stringWithFormat:@"%@user/logout/",kBaseURL];
  
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion};
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"SelfUidKey"];
        [XGPush unRegisterDevice];
        
        
//        [self clearUserInfo];
        
        for (UINavigationController *nav in self.tabBarController.viewControllers) {
            for(UIViewController *consult in nav.viewControllers)
            {
                if([consult isKindOfClass:[ConsultViewController class]])
                {
                    //清除咨询页面数据
                    ConsultViewController *consultVC=(ConsultViewController *)consult;
                    [consultVC clearInfo];
                    consultVC.myInfoDic=nil;
                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"SelfUidKey"];
                    //关闭websocket。
                    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
                    app.webSocket.delegate = nil;
                    [app.webSocket close];
                    [app.heartBeatTimer invalidate];
                    app.heartBeatTimer=nil;
                    //隐藏起泡
                    LCStatusBarOverlay *statusbar=[LCStatusBarOverlay shared];
                    [statusbar hidenMessageLabel];

                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNoticeNotification object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNewsNotification object:nil];
                }
            }
        }
        [self.navigationController popToRootViewControllerAnimated:YES];
        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

#pragma -mark 判读路径 
/**
 *  判断路径和大小
 *
 *  @param folderPath 无
 *
 *  @return 无
 */
- (float ) folderSizeAtPath:(NSString*) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    
    return 0;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
